package com.wstuo.common.tools.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.attachment.dao.IAttachmentDAO;
import com.wstuo.common.config.attachment.dto.AttachmentDTO;
import com.wstuo.common.config.attachment.entity.Attachment;
import com.wstuo.common.config.attachment.service.IAttachmentService;
import com.wstuo.common.tools.dao.IEventAttachmentDAO;
import com.wstuo.common.tools.dto.EventAttachmentDTO;
import com.wstuo.common.tools.entity.EventAttachment;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.util.StringUtils;

/**
 * Event Attachment Service class
 * @author WSTUO
 *
 */
public class EventAttachmentService implements IEventAttachmentService {
	private static final Logger LOGGER = Logger.getLogger(EventAttachmentService.class ); 
	@Autowired
	private IEventAttachmentDAO eventAttachmentDAO;
	@Autowired
	private IAttachmentDAO attachmentDAO;
	@Autowired
	private IAttachmentService attachmentService;

	/**
	 * 查询全部
	 * @param dto EventAttachmentDTO
	 * @return List<EventAttachment>
	 */
	@Transactional
    public List<EventAttachmentDTO> findAllEventAttachment(EventAttachmentDTO dto){
    	List<EventAttachmentDTO> eventAttachmentDtos=new ArrayList<EventAttachmentDTO>();
    	List<EventAttachment> eas=eventAttachmentDAO.findAllEventAttachment(dto);
		if(eas!=null){
			for(EventAttachment ea:eas){
				EventAttachmentDTO eventAttachmentDto=new EventAttachmentDTO();
				EventAttachmentDTO.entity2dto(ea,eventAttachmentDto);
				Attachment ac = ea.getAttachment();
				if(ac!=null){
					BeanUtils.copyProperties(ac, eventAttachmentDto);
				}
				eventAttachmentDtos.add(eventAttachmentDto);
			}
		}
		return eventAttachmentDtos;
    }

    /**
     * 删除附件
     * @param ids
     * @param eno
     */
    @Transactional
    public void deleteEventAttachment(final Long[] ids,Long eno){
    	List<EventAttachment> li=eventAttachmentDAO.findByEventAttachment(ids, eno);
    	for(EventAttachment att:li){
    		eventAttachmentDAO.delete(att);
    	}
    }
    
    /**
     * 保存附件
     * @param attachmentStr
     * @param eno
     * @param eventType
     */
	@Transactional
    public void saveEventAttachment(String createor,Long[] aids,String attachmentStr,Long eno,String eventType){
    	AttachmentDTO attachment = new AttachmentDTO();
    	attachment.setCreator(createor);
    	attachment.setType(eventType);
    	this.saveEventAttachment(attachment, aids, attachmentStr, eno);
    }
    @Transactional
    public void saveEventAttachment(AttachmentDTO attachment,Long[] aids,String attachmentStr,Long eno){
        if(attachmentStr!=null && attachmentStr.indexOf("-s-")!=-1){
        	String [] attrArr=attachmentStr.split("-s-");
    		for(int i=0;i<attrArr.length;i++){
    			String url=attrArr[i].replace("\\", "/");
				if(StringUtils.hasText(url)){
        			String [] attrArrs=url.split("==");
    				AttachmentDTO dto=new AttachmentDTO();
    				dto.setAttachmentName(attrArrs[0]);
    				dto.setType( attachment.getType() );
    				
    				Attachment ac=findAttachmentName(attachment, attrArrs);
                	//判断是否创建关系
                	boolean addEA=eventAttachmentboolean(ac.getAid(),eno);
                	//Save EventAttachemnt
                	if(addEA){
                		eventAttachmentsave(ac, eno, attachment.getType());
                	}
    			}
    		}
        }
        if(aids!=null){
        	for(Long aid:aids){
        		//判断是否创建关系
        		boolean addsEA=eventAttachmentboolean(aid,eno);
        		if(addsEA){
        			Attachment ac = attachmentDAO.findById(aid);
        			eventAttachmentsave(ac, eno, attachment.getType());
        		}
    		} 
        }
    }
    /**
     * 根据附件名称查询附件是否存在
     * @param attachment
     * @param attrArrs
     * @return
     */
    private Attachment findAttachmentName(AttachmentDTO attachment,String[] attrArrs){
    	//PageDTO pageDto = attachmentDAO.findattachmentPager(dto, 0, 100, "createTime", "desc");
		//List<Attachment> lis=(List<Attachment>)pageDto.getData();
		Attachment ac = new Attachment();
		ac.setDescription(attachment.getDescription());
		//boolean add = true;
		//if(lis!=null && lis.size()>0 && attachment.getType().equals(lis.get(0).getType())){
			//ac=lis.get(0);
			//add=false;
		//}
		ac=attachmenttransform(ac, attrArrs, attachment.getType(), attachment.getCreator() );
		//if(add){
    	attachmentDAO.save(ac);
    	//}else{
    		//attachmentDAO.merge(ac);
    	//}
    	return ac;
    }
    
    
    /**
     * 数据处理
     * @param aids
     * @param eno
     * @param eventType
     */
    @Transactional
    protected Attachment attachmenttransform(Attachment ac,String [] attrArrs,String eventType,String createor){
    	if(attrArrs.length>0){
    		if(!StringUtils.hasText(attrArrs[0].trim())){
        		ac.setAttachmentName(null); 
        	}else{
        		ac.setAttachmentName(attrArrs[0]);
        	}
    	}
    	if(attrArrs.length>1){
    		if(!StringUtils.hasText(attrArrs[1].trim())){
    			ac.setUrl(null);
    		}else{
    			ac.setUrl(attrArrs[1]);
    		}
    	}
    	if(attrArrs.length>2){
    		if(StringUtils.hasText(attrArrs[2])){//大小
        		ac.setSize(Long.valueOf(attrArrs[2]));
        	}else{
        		ac.setSize(0L);
        	}
    	}
    	if (attrArrs.length > 3) {//缩略图
    		ac.setDescription( attrArrs[3] ) ;
		}
    	ac.setCreator(createor);
    	ac.setCreateTime(new Date());
    	ac.setType(eventType);
    	return ac;
    }
    /**
     * 保存数据
     * @param aids
     * @param eno
     * @param eventType
     */
    @Transactional
    protected void eventAttachmentsave(Attachment ac,Long eno,String eventType){
    	EventAttachment ea = new EventAttachment();
		ea.setAttachment(ac);
		ea.setEno(eno);
		ea.setEventType(eventType);
    	eventAttachmentDAO.save(ea);
    }
    /**
     * 判断是否存在关系
     * @param aids
     * @param eno
     * @param eventType
     */
    @Transactional
    protected boolean eventAttachmentboolean(Long aid,Long eno){
    	boolean addsEA = true;
    	List<EventAttachment> li=eventAttachmentDAO.findBy("eno",eno);
    	for(EventAttachment e:li){
    		if(e.getAttachment().getAid().equals(aid)){
    			addsEA=false;
    		}
    	}
    	return addsEA;
    }
    /**
     * 保存附件
     * @param attachmentStr
     * @param eno
     * @param eventType
     */
    @Transactional
    public void saveEventAttachment(String attachmentStr,Long eno,String eventType){
    	
    }
    
    /**
     * 删除附件
     * @param aid
     * @return EventAttachment
     */
	public String deleteEventAttachmentByAid(Long aid,String filePath) {
    	try {
    		List<EventAttachment> eve = eventAttachmentDAO.findBy("attachment.aid", aid);
    		if(null != eve && eve.size() > 0){
    			/*for(EventAttachment att:eve){
    				eventAttachmentDAO.delete(att);
    			}*/
    			//存在关联不能删除
    			return "error";
    		}else{
    			attachmentService.deleteReturn(aid);
    			StringBuffer fileName = new StringBuffer();
    			fileName.append(AppConfigUtils.getInstance().getAttachmentPath()).append("/").append(filePath);
    			File file = new File(fileName.toString());
    			if (!file.isDirectory()) {
    				file.delete();
    			}
    			return "success";
    		}
		} catch (Exception e) {
			LOGGER.error(e);
		}
    	return "error";
	}

}
